<template>
<div>
  <!-- 第一步 - 发布公钥 -->
  <div class="task-container">
    <el-form ref="createForm" :model="dataForm" :rules="rules">
    <!-- 基本配置 -->
    <div class="data-show">
      <!-- 标题 -->
      <div class="data-actions">
        <h3>基本配置</h3>
      </div>
      <!-- 内容区 -->
      <div class="data-table">
        <!-- 通用布局行 -->
        <div class="common-row row-between">
          <!-- 配置项 - 任务名称 -->
          <div class="common-item item-3">
            <label class="condition-label">任务名称</label>
            <el-form-item class="condition-input" prop="name">
              <el-input :disabled="dataForm.done" type="text" placeholder="请输入任务名称" v-model="dataForm.name" />
            </el-form-item>
          </div>
          <!-- 配置项 - 平台 -->
          <div class="common-item item-3">
            <label class="condition-label">算法模块选择</label>
            <el-form-item class="condition-input" prop="system">
              <el-select :disabled="dataForm.done" v-model="dataForm.system" clearable placeholder="请选择平台">
                <el-option v-for="(item, index) in systems" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 配置项 - 类型 -->
          <div class="common-item item-3">
            <label class="condition-label">任务类型</label>
            <el-form-item class="condition-input" prop="type">
              <el-select :disabled="dataForm.done" v-model="dataForm.type" clearable placeholder="请选择类型">
                <el-option v-for="(item, index) in types" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <!-- 通用布局行 -->
        <div class="common-row">
          <div class="common-item item-10">
            <label class="condition-label">任务描述</label>
            <el-form-item class="condition-input" prop="description">
              <el-input :disabled="dataForm.done" v-model="dataForm.description" maxlength="100" type="textarea" show-word-limit :rows="4" resize="none" placeholder="请输入任务描述" />
            </el-form-item>
          </div>
        </div>
      </div>
    </div>
    <div class="data-show">
      <!-- 标题 -->
      <div class="data-actions">
        <h3>公钥发布</h3>
      </div>
      <div class="data-table">
        <!-- 通用布局行 -->
        <div class="common-row row-between">
          <!-- 配置项 - 发布用户 -->
          <div class="common-item item-5">
            <label class="condition-label">发布用户</label>
            <el-form-item class="condition-input" prop="userID">
              <el-input :disabled="dataForm.done" type="text" placeholder="请输入用户id" v-model="dataForm.userID" />
            </el-form-item>
          </div>
          <!-- 配置项 - 目标用户 -->
          <div class="common-item item-5">
            <label class="condition-label">目标用户</label>
            <el-form-item class="condition-input" prop="targetUserId">
              <el-input :disabled="dataForm.done" type="text" placeholder="请输入用户id" v-model="dataForm.targetUserId" />
            </el-form-item>
          </div>
        </div>
        <!-- 通用布局行 -->
        <div class="common-row row-between">
          <!-- 配置项 - 算法类型 -->
          <div class="common-item item-5">
            <label class="condition-label">算法模块</label>
            <el-form-item class="condition-input" prop="keyType">
              <el-select :disabled="dataForm.done" v-model="dataForm.keyType" clearable placeholder="请选择算法">
                <el-option v-for="(item, index) in keyTypes" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 配置项 - 参数文件 -->
          <div class="common-item item-5">
            <label class="condition-label">参数文件</label>
            <el-form-item class="condition-input" prop="config">
              <el-select :disabled="dataForm.done" v-model="dataForm.config" clearable placeholder="请选择参数">
                <el-option v-for="(item, index) in configs" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>
      </div>
    </div>

    <transition name="upload">
      <!-- 底部的按钮 -->
      <div class="btn-groups" v-if="!dataForm.done">
        <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
        <button :disabled="dataForm.createFlag" type="button" class="btn" @click="handleCreateTask">发布</button>
      </div>
      <!-- 展示公钥密文 -->
      <div v-else>
        <div class="data-show">
          <!-- 标题 -->
          <div class="data-actions data-title-between">
            <h3>公钥密文</h3>
            <div class="data-title-actions">
              <span class="action aniTxtBtn" @click="copyPublicKeyText">复制</span>
              <span class="action aniTxtBtn" @click="downloadPublicKeyText">下载</span>
            </div>
          </div>
          <div class="data-table data-table-scroll">
            <p class="text-container">
              {{ changeJSON(dataForm.publicKeyText) }}
            </p>
          </div>
        </div>
        <transition name="upload">
          <!-- 第二步的按钮 -->
          <div class="btn-groups" v-if="!shareKey.done">
            <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
            <button :disabled="shareKey.btnFlag" type="button" class="btn" @click="handleEmbeddingShareKey">嵌入私钥</button>
          </div>
          <div v-else>
            <div class="data-show">
              <!-- 标题 -->
              <div class="data-actions data-title-between">
                <h3>私钥密文</h3>
                <div class="data-title-actions">
                  <span class="action aniTxtBtn" @click="copySharedKeyText">复制</span>
                  <span class="action aniTxtBtn" @click="downloadSharedKeyText">下载</span>
                </div>
              </div>
              <div class="data-table data-table-scroll">
                <p class="text-container">
                  {{ changeJSON(shareKey.encryptedSharedKey) }}
                </p>
              </div>
            </div>
            <transition name="upload">
              <!-- 第三部的按钮 -->
              <div class="btn-groups" v-if="!signData.done">
                <button type="button" class="btn btn-normal" @click="handleCancel">取消</button>
                <button :disabled="signData.btnFlag" type="button" class="btn" @click="handleEmbeddingSign">发布签名</button>
              </div>
              <div v-else>
                <div class="data-show">
                  <!-- 标题 -->
                  <div class="data-actions data-title-between">
                    <h3>签名密文</h3>
                    <div class="data-title-actions">
                      <span class="action aniTxtBtn" @click="copySignText">复制</span>
                      <span class="action aniTxtBtn" @click="downloadSignText">下载</span>
                    </div>
                  </div>
                  <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(signData.signature) }}
                    </p>
                  </div>
                </div>
              </div>
            </transition>
          </div>
      </transition>
      </div>
    </transition>
    </el-form>
  </div>
</div>
</template>
<script setup>
import { ref, computed, onActivated } from 'vue';
import { API } from '@/utils/status.js';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as rule from '@/utils/rules';
import * as request from '@/api/steganography';
import useAppStore from '@/stores/app';

const appStore = useAppStore();
const router = useRouter();
const route = useRoute();
const defaultDataObj = {
  id: null,
  createFlag: false,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  targetUserId: null,
  keyType: null,
  config: null,
  publicKeyText: null,
  done: false
}
const defaultShareKeyObj = {
  done: false,
  btnFlag: false,
  encryptedSharedKey: null
};
const defaultSignObj = {
  done: false,
  btnFlag: false,
  signature: null
};
// 表单验证规则
const rules = {
  name: rule.taskNameRules,
  userID: rule.createRequired('用户不能为空'),
  targetUserId: rule.createRequired('用户不能为空'),
  keyType: rule.createRequired('算法不能为空')
};
const systems = API.steganography.systems;
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];
const configs = [
  { value: 'config1', label: '参数文件1' },
  { value: 'config2', label: '参数文件2' }
];
const keyTypes = API.publicSteg.keyTypes;

// ========> data <========
// 发布任务表单dom
const createForm = ref(null);
// 绑定表单对象
const dataForm = ref({
  id: null,
  createFlag: false,
  name: '',
  description: '',
  system: null,
  type: null,
  userID: null,
  targetUserId: null,
  keyType: null,
  config: null,
  publicKeyText: null,
  // 第一步是否完成
  /*
    展示publicKeyText
    隐藏发布及取消按钮
    显示第二步表单
    第一步表单全disabled
  */
  done: false
});
// 第二步控制对象
const shareKey = ref({
  done: false,
  btnFlag: false,
  encryptedSharedKey: null
});
// 第三部控制对象
const signData = ref({
  done: false,
  btnFlag: false,
  signature: null
});
const changeJSON = computed(() => {
  return function (jsonString){
    return jsonString ? window.decodeURIComponent(JSON.parse(jsonString)) : '';
  }
})


// ========> hooks <========
onActivated(() => {
  let { id, isCreate, reenter } = route.query;
  if (reenter || (id !== undefined && id == dataForm.value.id)){
    return;
  }
  if (isCreate){
    init();
    return;
  }
  reInit();
});

// ========> methods <========
function init(){
  dataForm.value = Object.assign({}, defaultDataObj);
  shareKey.value = Object.assign({}, defaultShareKeyObj);
  signData.value = Object.assign({}, defaultSignObj);
}

function reInit(){
  let {id} = route.query;
  init();
  request.getTaskDetailById({id})
    .then(res => {
      let result = res;
      result.infoData = JSON.parse(res.infoData);
      console.log(result)
      dataForm.value.id = result.id;
      dataForm.value.name = result.name;
      dataForm.value.description = result.description;
      dataForm.value.userID = result.infoData.userID;
      dataForm.value.targetUserId = result.infoData.targetUserId;
      dataForm.value.keyType = result.infoData.keyType;
      dataForm.value.config = result.infoData.config;
      dataForm.value.createFlag = false;
      if (result.infoData.publicKeyText){
        dataForm.value.publicKeyText = result.infoData.publicKeyText;
        dataForm.value.done = true;
      }
      if (result.infoData.encryptedSharedKey) {
        shareKey.value.done = true;
        shareKey.value.btnFlag = false;
        shareKey.value.encryptedSharedKey = result.infoData.encryptedSharedKey;
      }
      if (result.infoData.signature){
        signData.value.done = true;
        signData.value.btnFlag = false;
        signData.value.signature = result.infoData.signature;
      }
    })
    .catch(err => {
      console.log(err)
      ElMessage.error('初始化错误')
    })
}
// 第一步的发布 - 创建任务发布公钥
function handleCreateTask(){
  if (dataForm.value.createFlag){
    ElMessage.warning('当前正在执行公钥发布，请稍后');
    return;
  }
  createForm.value.validate(valid => {
    if (valid){
      dataForm.value.createFlag = true;
      appStore.openLoading('公钥发布中...');
      request.publicImplantPublicKey({
        name: dataForm.value.name,
        moduleType: API.steganography.moduleType.THREE,
        taskType: API.steganography.type.IMPLANT,
        description: dataForm.value.description,
        infoData: {
          userID: dataForm.value.userID,
          targetUserId: dataForm.value.targetUserId,
          keyType: dataForm.value.keyType,
          config: dataForm.value.config
        }
      })
        .then(res => {
          console.log(res)
          dataForm.value.createFlag = false;
          appStore.closeLoading();
          if (res && res.infoData && res.infoData.publicKeyText){
            ElMessage.success('公钥发布成功!');
            dataForm.value.id = res.id;
            dataForm.value.publicKeyText = res.infoData.publicKeyText;
            dataForm.value.done = true;
            console.log(res);
            console.log(dataForm.value)
          } else {
            ElMessage.error('获取公钥密文失败，请稍后重试或联系管理员');
          } 
        })
        .catch(err => {
          dataForm.value.createFlag = false;
          appStore.closeLoading();
        })
    } else {
      ElMessage.warning('填写信息有误，请核对后提交');
    }
  });
}
// 第一步 - 点击公钥密文的复制键
function copyPublicKeyText(){
  if (!dataForm.value.publicKeyText) {
    ElMessage.warning('公钥密文为空，请稍后再试或联系管理员');
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(dataForm.value.publicKeyText)
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = dataForm.value.publicKeyText;
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 第一步 - 点击公钥密文的下载键
function downloadPublicKeyText(){
  if (!dataForm.value.publicKeyText) {
    ElMessage.warning('公钥密文为空，请稍后再试或联系管理员');
    return;
  }
  const blob = new Blob([dataForm.value.publicKeyText], { type: 'application/json' });
  // const txt = new File([blob], 'publicKeyText.txt', { type: 'text/plain' });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = 'publicKeyText.json';
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
// 第二步 - 点击嵌入私钥
function handleEmbeddingShareKey(){
  if (!dataForm.value.id && dataForm.value.id !== 0 && dataForm.value.id !== '0'){
    ElMessage.error('嵌入任务不存在，请稍后重试或联系管理员');
    return;
  }
  if (shareKey.value.btnFlag){
    ElMessage.warning('当前正在进行私钥嵌入，请稍后');
    return;
  }
  shareKey.value.btnFlag = true;
  appStore.openLoading('私钥嵌入中...');
  request.publicImplantEmbeddingSharedKey({ id: dataForm.value.id })
    .then(res => {
      console.log(res);
      shareKey.value.btnFlag = false;
      appStore.closeLoading();
      if (res && res.infoData && res.infoData.encryptedSharedKey){
        ElMessage.success('嵌入私钥成功!');
        shareKey.value.encryptedSharedKey = res.infoData.encryptedSharedKey;
        shareKey.value.done = true;
      } else {
        ElMessage.error('嵌入私钥失败，请稍后重试或联系管理员');
      }
    })
    .catch(err => {
      console.log(err)
      shareKey.value.btnFlag = false;
      appStore.closeLoading();
    })
}
// 第二步 - 点击私钥密文复制
function copySharedKeyText(){
  if (!shareKey.value.encryptedSharedKey) {
    ElMessage.warning('私钥密文为空，请稍后再试或联系管理员');
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(shareKey.value.encryptedSharedKey)
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = shareKey.value.encryptedSharedKey;
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 第二步 - 点击私钥密文的下载键
function downloadSharedKeyText(){
  if (!shareKey.value.encryptedSharedKey) {
    ElMessage.warning('私钥密文为空，请稍后再试或联系管理员');
    return;
  }
  const blob = new Blob([shareKey.value.encryptedSharedKey], { type: 'application/json' });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = 'encryptedSharedKey.json';
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
// 第三部 - 发布签名
function handleEmbeddingSign(){
  if (dataForm.value.id !== 0 && dataForm.value.id !== '0' && !dataForm.value.id){
    ElMessage.error('嵌入任务不存在，请稍后重试或联系管理员');
    return;
  }
  if (signData.value.btnFlag){
    ElMessage.warning('当前正在进行签名，请稍后');
    return;
  }
  signData.value.btnFlag = true;
  appStore.openLoading('签名中...');
  request.publicImplantEmbeddingSign({
    id: dataForm.value.id
  })
    .then(res => {
      console.log(res);
      signData.value.btnFlag = false;
      appStore.closeLoading();
      if (res && res.infoData && res.infoData.signature){
        ElMessage.success('签名发布成功');
        signData.value.signature = res.infoData.signature;
        signData.value.done = true;
      } else {
        ElMessage.error('签名发布失败，请稍后重试或联系管理员');
      }
    })
    .catch(err => {
      console.log(err);
      signData.value.btnFlag = false;
      appStore.closeLoading();
    })
}
// 第三部 - 点击签名复制
function copySignText(){
  if (!signData.value.signature) {
    ElMessage.warning('私钥密文为空，请稍后再试或联系管理员');
    return;
  }
  if (navigation.clipboard){
    navigation.clipboard.writeText(signData.value.signature)
      .then(res => {
        ElMessage.success('已复制到剪切板');
      })
      .catch(err => {
        ElMessage.error('复制失败');
      })
  } else if (document.execCommand){
    const textarea = document.createElement('textarea');
    textarea.value = signData.value.signature;
    document.body.appendChild(textarea);
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful){
        ElMessage.success('已复制到剪切板');
      } else {
        ElMessage.error('复制失败');
      }
    } catch(err){
      console.log('sss')
      ElMessage.error(err);
    }
    document.body.removeChild(textarea); 
  }
}
// 第三部 - 点击签名下载
function downloadSignText(){
  if (!signData.value.signature) {
    ElMessage.warning('签名为空，请稍后再试或联系管理员');
    return;
  }
  const blob = new Blob([signData.value.signature], { type: 'application/json' });
  const link = document.createElement('a');
  const fileUrl = window.URL.createObjectURL(blob);
  link.href = fileUrl;
  link.download = 'signature.json';
  ElMessage.success('下载开始');
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
// 点击取消按钮
function handleCancel(){
  router.back();
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 10px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.item-10-spe {
  width: 100%;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
  &::v-deep .el-form-item__content {
    align-items: center!important;
  }
}
.item-5 {
  width: 49%;
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.condition-label-change {
  cursor: pointer;
}
.condition-label-change:hover {
  color: var(--color-primary);
}
.data-title-between {
  @include flex-between-center;
  .data-title-actions {
    display: flex;
  }
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
}
</style>